<template>
  <h1 class="text-xl font-semibold leading-7 text-gray-900 mt-5">
    {{ $t('pageNetwork.ipv4') }}
  </h1>
  <h1 class="text-sm leading-7 text-gray-900">
    {{ $t('pageNetwork.ipv4Addresses') }}
  </h1>
  <el-row justify="end" class="mb-2">
    <el-button type="primary" :icon="Setting" @click="switchToDHCP">
      {{ $t('pageNetwork.table.switchToDHCP') }}
    </el-button>
    <el-button type="primary" :icon="CirclePlus" @click="initAddIpv4Address">
      {{ $t('pageNetwork.table.addIpv4Address') }}
    </el-button>
  </el-row>

  <el-table
    ref="tableRef"
    row-key="groupName"
    style="width: 100%"
    :data="form.ipv4TableItems"
    border
  >
    <el-table-column
      prop="Address"
      :label="$t('pageNetwork.table.ipAddress')"
    />
    <el-table-column prop="Gateway" :label="$t('pageNetwork.table.gateway')" />
    <el-table-column
      prop="SubnetMask"
      :label="$t('pageNetwork.table.subnet')"
    />
    <el-table-column
      prop="AddressOrigin"
      :label="$t('pageNetwork.table.addressOrigin')"
    />
    <el-table-column label="Operations">
      <template #default="scope">
        <el-button
          size="small"
          type="danger"
          class="bg-orange-600"
          @click="deleteIpv4TableRow(scope.$index)"
          >{{ $t('global.action.delete') }}</el-button
        >
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { CirclePlus } from '@element-plus/icons-vue';
import { Setting } from '@element-plus/icons-vue';
import { reactive } from 'vue';
import { useNetworkStore } from '@/store/Settings/NetworkStore';
import { useI18n } from 'vue-i18n';

const i18n = useI18n();
const networkStore = useNetworkStore();

const props = defineProps<{ tabIndex: number }>();

const ethernetData = computed(() => networkStore.ethernetData);

const emit = defineEmits(['open-ipv4']);
const form = reactive({
  ipv4TableItems: [],
});

const getIpv4TableItems = () => {
  const index = props.tabIndex;
  const addresses = ethernetData.value[index].IPv4Addresses || [];
  form.ipv4TableItems = addresses.map(
    (ipv4: {
      Address: any;
      SubnetMask: any;
      Gateway: any;
      AddressOrigin: any;
    }) => {
      return {
        Address: ipv4.Address,
        SubnetMask: ipv4.SubnetMask,
        Gateway: ipv4.Gateway,
        AddressOrigin: ipv4.AddressOrigin,
        actions: [
          {
            value: 'delete',
            title: i18n.t('pageNetwork.table.deleteIpv4'),
          },
        ],
      };
    },
  );
};

const switchToDHCP = () => {
  networkStore
    .awakeDHCP()
    .then((message: string) =>
      ElNotification({
        title: 'Success',
        message,
        type: 'success',
      }),
    )
    .catch(({ message }: { message: string }) =>
      ElNotification({
        title: 'Error',
        message,
        type: 'error',
      }),
    );
};
const deleteIpv4TableRow = (index: number) => {
  form.ipv4TableItems.splice(index, 1);
  const newIpv4Array = form.ipv4TableItems.map(
    (ipv4: { Address: any; SubnetMask: any; Gateway: any }) => {
      const { Address, SubnetMask, Gateway } = ipv4;
      return {
        Address,
        SubnetMask,
        Gateway,
      };
    },
  );
  networkStore
    .editIpv4Address(newIpv4Array)
    .then((message: string) =>
      ElNotification({
        title: 'Success',
        message,
        type: 'success',
      }),
    )
    .catch(({ message }: { message: string }) =>
      ElNotification({
        title: 'Error',
        message,
        type: 'error',
      }),
    );
};

const initAddIpv4Address = () => {
  emit('open-ipv4');
};

getIpv4TableItems();

watch(
  () => props.tabIndex,
  () => getIpv4TableItems(),
);
watch(ethernetData, () => getIpv4TableItems());
watch(form, () => {
  if (form.ipv4TableItems.length == 1) {
    nextTick(() => {
      const dom: any = document.querySelector(
        '.tab-pane.active .tableIpv4-action > button',
      );
      if (dom) dom.disabled = true;
    });
  } else {
    nextTick(() => {
      const dom: any = document.querySelector(
        '.tab-pane.active .tableIpv4-action > button',
      );
      if (dom) dom.disabled = false;
    });
  }
});
</script>
